# requests>urllib>socket
import selectors
import socket
from urllib.parse import urlparse
from selectors import DefaultSelector

def get_content(url):
    url = urlparse(url)
    host=url.netloc
    path=url.path
    if path=="":
        path="/"


    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((host, 80))
    client_socket.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host).encode())
    data=b""
    while True:
        d = client_socket.recv(1024)
        if not d:
            break
        data += d

    print(data.decode())
    client_socket.close()



class Fether:
    def __init__(self):
        self.selector = DefaultSelector()
        self.client_socket=None
        self.host=""
        self.path=""
        self.data=b""


    def connected(self,key):
        #取消注册
        self.selector.unregister(key.fd)

        # 注册读事件
        self.selector.register(self.client_socket, selectors.EVENT_READ, self.readable)

        #已连接成功，发送数据,这里是非阻塞的，需要注册
        self.client_socket.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(self.path, self.host).encode())



    def readable(self,key):
        d = self.client_socket.recv(1024)
        if d:
            self.data+=d
        else:
            self.selector.unregister(key.fd)
            print(self.data.decode())


    def get_url(self,url):
        url = urlparse(url)
        self.host = url.netloc
        path = url.path
        if path == "":
            path = "/"
        self.path = path

        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.setblocking(False)

        # 注册连接事件
        self.selector.register(self.client_socket.fileno(), selectors.EVENT_WRITE, self.connected)
        # 执行连接
        try:
            self.client_socket.connect((self.host, 80))
        except BlockingIOError:
            pass





    def loop(self):
        try:
            while True:
                ready=self.selector.select()
                for key, mask in ready:
                    callback=key.data
                    callback(key)
        except KeyboardInterrupt:
            pass


if __name__=="__main__":
    fether=Fether()
    fether.get_url("http://www.baidu.com")
    fether.loop()